package com.a2.appa3.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.a2.appa3.R;
import com.a2.appa3.dagger.component.activity.DaggerLoginActivityComponent;
import com.a2.appa3.dagger.module.activity.LoginActivityModule;
import com.a2.appa3.model.network.entity.req.ResCode;
import com.a2.appa3.model.network.entity.req.ResLogin;
import com.a2.appa3.model.network.entity.req.Restyelogin;
import com.a2.appa3.presenter.activity.LoginActivityPresenter;
import com.a2.appa3.util.CheckOutDialog;
import com.a2.appa3.util.EventBus.Eventnumber;
import com.a2.appa3.util.Md5;
import com.a2.appa3.util.SpUtils;
import com.a2.appa3.widget.CheckOutView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import me.shihao.library.XStatusBarHelper;

public class LoginActivity extends BaseActivity<LoginActivityPresenter> {

    @BindView(R.id.ivback)
    ImageView back;
    @BindView(R.id.headerTitle)
    TextView headerTitle;
    @BindView(R.id.headerButton)
    ImageView headerButton;
    @BindView(R.id.headerButtonRoot)
    LinearLayout headerButtonRoot;
    @BindView(R.id.logintitle)
    TextView logintitle;
    @BindView(R.id.user_name_et)
    EditText userNameEt;
    @BindView(R.id.onclockimg)
    ImageView onclockimg;
    @BindView(R.id.user_pass_et)
    EditText userPassEt;
    @BindView(R.id.play_bt)
    TextView playBt;
    @BindView(R.id.loginlayout)
    LinearLayout loginlayout;
    @BindView(R.id.loginbt)
    TextView loginbt;
    @BindView(R.id.rigisterbt)
    TextView rigisterbt;
    @BindView(R.id.yearpass)
    CheckBox yearpass;
    @BindView(R.id.savepass)
    CheckBox savepass;
    @BindView(R.id.Scrowlogin)
    View Scrowlogin;
    @BindView(R.id.onclockimg1)
    ImageView onclockimg1;
    @BindView(R.id.code_et)
    EditText codeEt;
    @BindView(R.id.code_img)
    ImageView code_img;
    @BindView(R.id.VerificationLinea)
    LinearLayout VerificationLinea;
    private String username;
    private String password;
    String[] code_reslut;
    CheckOutDialog dialog = new CheckOutDialog();
    public boolean TAG = false; //默认为滑块模式否为数字验证模式
    private String numberpassport;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        if (android.os.Build.VERSION.SDK_INT >= 21) {
            //解决Android5.0以上，状态栏设置颜色后变灰的问题
            XStatusBarHelper.tintStatusBar(this, getResources().getColor(R.color.settingbg));
        }
        //获取使用图形还是数字验证
        mPresenter.getberifystatus();
        InitView();
    }

    private void InitView() {
        headerTitle.setText("登录");
        back.setVisibility(View.INVISIBLE);
//        code_reslut = code_img.getValidataAndSetImage();//生成验证码
        code_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.getCode();
            }
        });
        String str = SpUtils.getString(LoginActivity.this, "loginpass", "");
        if (str.equals("1")) {
            savepass.setChecked(true);
            userNameEt.setText("" + SpUtils.getString(LoginActivity.this, "username", ""));
            userPassEt.setText("" + SpUtils.getString(LoginActivity.this, "password", ""));
        } else {
            savepass.setChecked(false);
        }

        userNameEt.setOnFocusChangeListener(new View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    Scrowlogin.setVisibility(View.VISIBLE);
                } else {
                    Scrowlogin.setVisibility(View.GONE);
                }
            }
        });
        userPassEt.setOnFocusChangeListener(new View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    Scrowlogin.setVisibility(View.VISIBLE);
                } else {
                    Scrowlogin.setVisibility(View.GONE);
                }
            }
        });
        codeEt.setOnFocusChangeListener(new View.
                OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    Scrowlogin.setVisibility(View.VISIBLE);
                } else {
                    Scrowlogin.setVisibility(View.GONE);
                }
            }
        });
        yearpass.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int passwordLength = userPassEt.getText().length();
                userPassEt.setInputType(isChecked ?
                        (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) :
                        (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD));
                userPassEt.setSelection(passwordLength);
            }
        });

    }

    @Override
    protected void initDagger() {
        DaggerLoginActivityComponent.builder()
                .loginActivityModule(new LoginActivityModule(this))
                .build().inject(this);
    }


    @Override
    protected int setContentView() {
        return R.layout.activity_login;
    }

    @OnClick({R.id.back, R.id.play_bt, R.id.loginbt, R.id.rigisterbt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.play_bt:
                startActivity(new Intent(LoginActivity.this, ForgetActivity.class));
                break;
            case R.id.loginbt:
                password = Md5.toMd5(userPassEt.getText().toString().trim());
                username = userNameEt.getText().toString().trim();

                if (!TextUtils.isEmpty(password) && !TextUtils.isEmpty(username)) {
                    if (savepass.isChecked()) {
//                    SYSOUtils.sOut_("保存密码");
                        SpUtils.putString(LoginActivity.this, "username", username);
                        SpUtils.putString(LoginActivity.this, "password", userPassEt.getText().toString().trim());
                        SpUtils.putString(LoginActivity.this, "loginpass", "1");//记录复选框状态
                    } else {
                        SpUtils.clearusername(this);
                        SpUtils.clearpassword(this);
                        SpUtils.clearloginpass(this);
                    }
                    if (TAG) {
                        mPresenter.login(username, password, codeEt.getText().toString().trim(), numberpassport + "");
                    } else {
                        mPresenter.getSlideVerify();
                    }
                } else {
                    Toast.makeText(this, "您未输入用户名或密码", Toast.LENGTH_SHORT);
                }
                break;
            case R.id.rigisterbt:
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                break;
        }
    }

    /**
     * 滑动验证
     *
     * @param restyelogin
     */
    public void SlideVerifyback(Restyelogin restyelogin) {
        int index = restyelogin.bg_pic.url.indexOf(",");
        String bg_picurl = restyelogin.bg_pic.url.substring(index + 1);

        int index1 = restyelogin.ico_pic.url.indexOf(",");
        String ico_picurl = restyelogin.ico_pic.url.substring(index1 + 1);
        dialog.init(bg_picurl,
                restyelogin.bg_pic.w,
                restyelogin.bg_pic.h,
                ico_picurl,
                restyelogin.ico_pic.w,
                restyelogin.ico_pic.h,
                restyelogin.y_point
        );
        dialog.setCheckOutListener(new CheckOutView.CheckOutListener() {
            @Override
            public void seekEnd(float value) {
                mPresenter.login(username, password, value + "", restyelogin.passport + "");
            }
        });
        dialog.show(getSupportFragmentManager(), "1");

    }


    public void onfail(ResLogin resLogin) {
        //登录失败了
        Toast.makeText(this, resLogin.msg, Toast.LENGTH_SHORT).show();
    }

    public void onsuccess() {
        startActivity(new Intent(LoginActivity.this, MainActivity.class));
        Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
        finish();
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(Eventnumber eventnumber) {
        if (eventnumber.number.equals("2")) {
            //注册后登录成功杀死该页面
            finish();
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void berifystatusback(String loginVerType) {
        //默认为0滑块模式，1为数字验证模式
        if ("0".equals(loginVerType)) {
            //隐藏
            VerificationLinea.setVisibility(View.GONE);
            TAG = false;
        } else {
            //放出来
            VerificationLinea.setVisibility(View.VISIBLE);
            TAG = true;
            mPresenter.getCode();
        }
    }

    /**
     * 数字验证码
     *
     * @param resCode
     */
    public void onCode(ResCode resCode) {
        numberpassport = "";
        numberpassport = resCode.data.captcha_code;
        Bitmap bitmap = null;
        byte[] bitmapArray;
        bitmapArray = Base64.decode(resCode.data.code, Base64.NO_WRAP);
        bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        code_img.setImageBitmap(bitmap);//显示图片
    }
}
